# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        l1 = self.get_list(l1, end_data=[])
        l2 = self.get_list(l2, end_data=[])
        min_len = max(len(l1), len(l2))
        n = 0
        end = []
        for i in range(min_len):
            if len(l1) <= i:
                num, n = self.add_(num1=l2[i], num2=0, n=n)
                end.append(num)
            elif len(l2) <= i:
                num, n = self.add_(num1=l1[i], num2=0, n=n)
                end.append(num)
            else:
                try:
                    num, n = self.add_(num1=l1[i], num2=l2[i], n=n)
                except Exception as e:
                    print(e)
                    pass
                end.append(num)
        if n:
            end.append(n)
        print(end)
        return self.text(end)

    def get_list(self, data: Optional[ListNode], end_data: list = []):
        next_list = data.next
        value = data.val
        end_data.append(value)
        if next_list:
            end_data = self.get_list(next_list, end_data)
        return end_data

    def add_(self, num1, num2, n):
        num = int((num1 + num2 + n) / 10)
        n = (num1 + num2 + n) % 10
        if num:
            return n, num
        else:
            return n, 0
        # return (num1 + num2 + n) / 10, (num1 + num2 + n) % 10

    def text(self, a: list):
        num = a[-1]
        num_list = a[:-1]

        next_value = ListNode(val=num, next=None)
        e = next_value
        for i in num_list[::-1]:
            e = ListNode(val=i, next=next_value)
            next_value = e
        return e


